# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
from users.models import User
from users.utils import generic_verify_url, check_active_token


class ResgiterUsernameAPIView(APIView):

    def get(self,request,username):
        count = User.objects.filter(username = username).count()

        data = {
            "count":count,
            "username":username
        }

        return Response(data)


class ResgiterMobileAPIView(APIView):

    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()

        data = {
            "count":count,
            "phone":mobile
        }

        return Response(data)


from .serializers import RegisterUserSerializer, UserCenterInfoSerializer, EmailUpdateSerializer, \
    AddressSerializer, SKUSerializer, AddressTitleSerializer
from rest_framework.generics import CreateAPIView


# class RegisterUserAPIView(APIView):
#
#     def post(self,request):
#
#         data = request.data
#
#         serializer = RegisterUserSerializer(data=data)
#         serializer.is_valid()

        # user = serializer.save()
        #
        # from rest_framework_jwt.settings import api_settings
        #
        # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        #
        # payload = jwt_payload_handler(user)
        # token = jwt_encode_handler(payload)

        # data =serializer.data
        # data["token"] = token

        # return Response(data)

class RegisterUserAPIView(CreateAPIView):

    serializer_class = RegisterUserSerializer


from rest_framework.permissions import IsAuthenticated


# class UserCenterInfoAPIView(APIView):
#
#     permission_classes = [IsAuthenticated]
#
#     def get(self,request):
#
#         user = request.user
#         serializer= UserCenterInfoSerializer(user)
#
#         return Response(serializer.data)


#三级视图
from rest_framework.generics import RetrieveAPIView
class UserCenterInfoAPIView(RetrieveAPIView):

    permission_classes = [IsAuthenticated]
    serializer_class = UserCenterInfoSerializer

    #重写Mixin中 get_object方法
    def get_object(self):

        return self.request.user


class EmailUpdateAPIView(APIView):

    permission_classes = [IsAuthenticated]

    def put(self,request):

        data = request.data
        user = request.user

        serializer = EmailUpdateSerializer(instance=user,data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # from django.core.mail import send_mail
        #
        # subject = '美多商场激活邮件'
        # message = ''
        # from_email = '美多商城<ragnarok@163.com>'
        # email = request.data.get('email')
        # recipient_list = [email]
        #
        # verify_url = generic_verify_url(request.user.id, email)
        #
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        #
        # send_mail(subject=subject,
        #           message=message,
        #           from_email=from_email,
        #           recipient_list=recipient_list,
        #           html_message=html_message)

        email = request.data.get('email')
        recipient_list = [email]

        verify_url = generic_verify_url(request.user.id, email)
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        from celery_tasks.email.tasks import send_email

        send_email.delay(recipient_list, html_message)

        return Response(serializer.data)


class EmailVerificationAPIView(APIView):

    def get(self,request):

        token = request.query_params.get("token")
        if token is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        data = check_active_token(token)

        if data is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        user_id  = data.get('user_id')
        email = data.get('email')

        try:
            user= User.objects.get(id = user_id,email = email)
        except Exception:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user.email_active = True
        user.save()

        return Response({"message":"ok"})


from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from .serializers import AddressSerializer

class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    #制定序列化器
    serializer_class = AddressSerializer
    #添加用户权限
    permission_classes = [IsAuthenticated]
    #由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)


    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })


    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


from rest_framework.generics import CreateAPIView
from .serializers import  UserHistroySerializer
from rest_framework.permissions import IsAuthenticated

class UserHistoryView(CreateAPIView):
    """
    用户浏览历史记录
    POST /users/browerhistories/
    GET  /users/browerhistories/
    数据只需要保存到redis中
    """
    serializer_class = UserHistroySerializer
    permission_classes = [IsAuthenticated]

    def get(self,request):

        user = request.user
        redis_conn = get_redis_connection('history')
        ids = redis_conn.lrange('history_%s' % user.id, 0, 4)

        skus = []
        for sku_id in ids:
            sku = SKU.objects.get(pk=sku_id)
            skus.append(sku)

        serializer = SKUSerializer(skus, many=True)

        return Response(serializer.data)

from rest_framework_jwt.views import ObtainJSONWebToken
from cart.utils import merge_cookie_to_redis


class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):

        response = super().post(request)

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():

            user = serializer.validated_data.get("user")
            response = merge_cookie_to_redis(request, user, response)

        return response